The goal in this competition is to take an image of a handwritten single digit, and determine what that digit is. As the competition progresses, we will release tutorials which explain different machine learning algorithms and help you to get started.
The data for this competition were taken from the MNIST dataset. The MNIST ("Modified National Institute of Standards and Technology") dataset is a classic within the Machine Learning community that has been extensively studied. More detail about the dataset, including Machine Learning algorithms that have been tried on it and their levels of success, can be found at http://yann.lecun.com/exdb/mnist/index.html.
| File Name | Available Formats |
|---|---|
| train | .csv (73.22 mb) |
| test | .csv (48.75 mb) |
The data files train.csv and test.csv contain gray-scale images of hand-drawn digits, from zero through nine.
Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255, inclusive.
The training data set, (train.csv), has 785 columns. The first column, called "label", is the digit that was drawn by the user. The rest of the columns contain the pixel-values of the associated image.
Each pixel column in the training set has a name like pixelx, where x is an integer between 0 and 783, inclusive. To locate this pixel on the image, suppose that we have decomposed x as x = i * 28 + j, where i and j are integers between 0 and 27, inclusive. Then pixelx is located on row i and column j of a 28 x 28 matrix, (indexing by zero).
For example, pixel31 indicates the pixel that is in the fourth column from the left, and the second row from the top, as in the ascii-diagram below.
Visually, if we omit the "pixel" prefix, the pixels make up the image like this:
000 001 002 003 ... 026 027 028 029 030 031 ... 054 055 056 057 058 059 ... 082 083 | | | | ... | | 728 729 730 731 ... 754 755 756 757 758 759 ... 782 783
The test data set, (test.csv), is the same as the training set, except that it does not contain the "label" column.
Your submission file should be in the following format: For each of the 28000 images in the test set, output a single line with the digit you predict. For example, if you predict that the first image is of a 3, the second image is of a 7, and the third image is of a 8, then your submission file would look like:
3 7 8 (27997 more lines)
The evaluation metric for this contest is the categorization accuracy, or the proportion of test images that are correctly classified. For example, a categorization accuracy of 0.97 indicates that you have correctly classified all but 3% of the images.
We will first explore the labled DataSet.
In [2]:
import pandas as pd
train_data=pd.read_csv('/train.csv')
train_data.head()
Out[2]:
In [3]:
train_data.tail()
Out[3]:
In [4]:
train_data.dtypes
Out[4]:
In [5]:
train_data.info()
Now that we already have general idea of Data Set. Let's work with features
In [6]:
train_features=train_data.values[:,1:]
train_target=train_data.label
train_target[:5]
Out[6]:
First let's try to plot digit from first 5 data point
In [7]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def plot_img(sample):
fig=plt.figure(figsize=(10,10))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1,hspace=0.05, wspace=0.05)
for i in range(sample.shape[0]):
img=np.reshape(sample[i],(28,28))
p=fig.add_subplot(sample.shape[0],sample.shape[0],i+1, xticks=[],
yticks=[])
p.imshow(img,cmap=plt.cm.bone)
plot_img(train_features[0:5])
Now, we shall try to reduce dimensionality of all features from 'pixel0' to 'pixel783' by using Principal component analysis (PCA), PCA is an orthogonal linear transformation that turns a set of possibly correlated variables into a new set of variables that are as uncorrelated as possible.
there are several class to implement different kind of PCA in sklearn but we will work with PCA class.
In [21]:
from sklearn.decomposition import PCA
my_pca=PCA(n_components=0.9)
pca_train_features=my_pca.fit_transform(train_features)
pca_train_features.shape
Out[21]:
Number of features has reduced from 784 to 87
In [22]:
from sklearn.cluster import KMeans
model=KMeans(init='k-means++')
model.fit(pca_train_features,train_target)
Out[22]:
In [25]:
#features from test data
test_data=pd.read_csv('/test.csv')
test_features=test_data.values[:,;]
pca_test_features=my_pca.transform(test_features)
#predicting original test set.
prediction=model.predict(pca_test_features)
In [ ]:
#preparing submission file
pd.DataFrame({"ImageId": range(1,len(prediction)+1), "Label": prediction}).to_csv('first_attempt.csv', index=False, header=True)
In [1]:
from sklearn.cross_validation import train_test_split
# Split 80-20 train vs test data
split_train_features, split_test_features, split_train_target, split_test_target= train_test_split(train_features,train_target,test_size=0.20,random_state=0)
In [2]:
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
#pre-processing split train
my_pca=PCA(n_components=0.9)
pca_split_train_features=my_pca.fit_transform(split_train_features)
#pre-processing split test features
pca_split_test_features=my_pca.transform(split_test_features)
#fit and predict using split data
model=KMeans(init='k-means++')
model.fit(pca_split_train_features,split_train_target)
split_prediction=model.predict(pca_split_test_features)
score=accuracy_score(split_test_target, split_prediction)
print (score(split_test_target, split_prediction))
Class KMeans has a parameter 'n_clusters', representing the number of clusters to form as well as the number of centroids to generate. We could use elbow method to select number of clusters in KMeans model.
In [4]:
from scipy import cluster
#using elbow method to select number of clusters in KMeans model
initial = [cluster.vq.kmeans(pca_train_features,i) for i in range(1,10)]
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot([var for (cent,var) in initial])
plt.grid(True)
plt.xlabel('Number of clusters')
plt.ylabel('distortion')
plt.title('Elbow for K-means clustering')
plt.show()
In [ ]: